#!/bin/sh
set -e

wpEnvs=( "${!WORDPRESS_@}" )

if [ "${#wpEnvs[@]}" -gt 0 ]; then
  cp -f /var/www/html/wp-config-sample.php /var/www/html/wp-config.php

  # Database settings
  if [ -n "$WORDPRESS_DB_HOST" ]; then
    sed -i 's/localhost/'$WORDPRESS_DB_HOST'/g' /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_DB_NAME" ]; then
    sed -i 's/database_name_here/'$WORDPRESS_DB_NAME'/g' /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_DB_USER" ]; then
    sed -i 's/username_here/'$WORDPRESS_DB_USER'/g' /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_DB_PASSWORD" ]; then
    sed -i 's/password_here/'$WORDPRESS_DB_PASSWORD'/g' /var/www/html/wp-config.php 
  fi

  # WordPress database table prefix
  if [ -n "$WORDPRESS_TABLE_PREFIX" ]; then
    sed -i "s/table_prefix = 'wp_'/table_prefix = '$WORDPRESS_DB_PASSWORD'/g" /var/www/html/wp-config.php 
  fi

  # WordPress debugging mode.
  if [ -n "$WORDPRESS_DEBUG" ]; then
    sed -i "s/'WP_DEBUG', false/'WP_DEBUG', true/g" /var/www/html/wp-config.php 
  fi

  # Authentication unique keys and salts.
  if [ -n "$WORDPRESS_AUTH_KEY" ]; then
    sed -i "s/'AUTH_KEY',\s*'put your unique phrase here'/'AUTH_KEY', '$WORDPRESS_AUTH_KEY'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_SECURE_AUTH_KEY" ]; then
    sed -i "s/'SECURE_AUTH_KEY',\s*'put your unique phrase here'/'SECURE_AUTH_KEY', '$WORDPRESS_SECURE_AUTH_KEY'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_LOGGED_IN_KEY" ]; then
    sed -i "s/'LOGGED_IN_KEY',\s*'put your unique phrase here'/'LOGGED_IN_KEY', '$WORDPRESS_LOGGED_IN_KEY'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_NONCE_KEY" ]; then
    sed -i "s/'NONCE_KEY',\s*'put your unique phrase here'/'NONCE_KEY', '$WORDPRESS_NONCE_KEY'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_AUTH_SALT" ]; then
    sed -i "s/'AUTH_SALT',\s*'put your unique phrase here'/'AUTH_SALT', '$WORDPRESS_AUTH_SALT'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_SECURE_AUTH_SALT" ]; then
    sed -i "s/'SECURE_AUTH_SALT',\s*'put your unique phrase here'/'SECURE_AUTH_SALT', '$WORDPRESS_SECURE_AUTH_SALT'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_LOGGED_IN_SALT" ]; then
    sed -i "s/'LOGGED_IN_SALT',\s*'put your unique phrase here'/'LOGGED_IN_SALT', '$WORDPRESS_LOGGED_IN_SALT'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_NONCE_SALT" ]; then
    sed -i "s/'NONCE_SALT',\s*'put your unique phrase here'/'NONCE_SALT', '$WORDPRESS_NONCE_SALT'/g" /var/www/html/wp-config.php 
  fi

  if [ -n "$WORDPRESS_NONCE_SALT" ]; then
    sed -i "s/'NONCE_SALT',\s*'put your unique phrase here'/'NONCE_SALT', '$WORDPRESS_NONCE_SALT'/g" /var/www/html/wp-config.php 
  fi

  chown apache:apache /var/www/html/wp-config.php
fi

php-fpm

# Apache gets grumpy about PID files pre-existing
rm -f /etc/httpd/run/httpd.pid

exec httpd -DFOREGROUND
